package com.nengchuan.kbms.dfs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.common.PageServiceImpl;
import com.nengchuan.kbms.dfs.constant.BaseConstant;
import com.nengchuan.kbms.dfs.dao.UserFavoriteMapper;
import com.nengchuan.kbms.dfs.entity.dto.BizDTO;
import com.nengchuan.kbms.dfs.entity.dto.UserFavoriteDTO;
import com.nengchuan.kbms.dfs.entity.po.UserFavorite;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 文件收藏 服务实现类
 * </p>
 *
 * @author abe
 * @since 2020-03-31
 */
@Service
public class UserFavoriteServiceImpl extends PageServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {

    @Autowired
    private UserFolderService userFolderService;

    @Autowired
    private DataFileService dataFileService;

    @Autowired
    private DataFolderService dataFolderService;

    /**
     * 收藏逻辑：
     * // TODO 权限验证
     * 1. 通过 bizType & bizId & craeteId 验证数据是否存在，如果存在说明已收藏，提示用户该文件（夹）已收藏
     * 2. ?? 如果 收藏的文件（夹）属于该用户已收藏的文件夹的一个子集需要询问业务是否能够收藏（// TODO）
     * 3. 收藏文件（夹）
     * @param userFavoriteDTO
     * @return
     */
    @Override
    public boolean collect(UserFavoriteDTO userFavoriteDTO) {
        Objects.requireNonNull(userFavoriteDTO);

        if (CollectionUtils.isEmpty(userFavoriteDTO.getBiz())) {
            throw new NcException("参数错误");
        }

        // 验证用户文件夹是否存在
        userFolderService.assertFolderExisted(userFavoriteDTO.getUserFolderId());

        // 同一目录下不允许收藏同一个文件
        List<Long> bizIdList = userFavoriteDTO.getBiz().stream().map(BizDTO::getBizId).collect(Collectors.toList());
        QueryWrapper<UserFavorite> wrapper = new QueryWrapper<>();
        wrapper.lambda().select(UserFavorite::getBizId).eq(UserFavorite::getUserFolderId, userFavoriteDTO.getUserFolderId())
                .in(UserFavorite::getBizId, bizIdList);
        list(wrapper).forEach(userFavorite -> userFavoriteDTO.getBiz().removeIf(biz -> userFavorite.getBizId().equals(biz.getBizId())));

        List<UserFavorite> userFavoriteList = userFavoriteDTO.getBiz().stream().map(biz -> {
            String fileName = null;
            if (BaseConstant.BizType.f.equals(biz.getBizType())) {
                fileName = dataFileService.assertFileExisted(biz.getBizId()).getFileName();
            } else if (BaseConstant.BizType.d.equals(biz.getBizType())) {
                fileName = dataFolderService.assertFolderExisted(biz.getBizId()).getFolderName();
            }
            UserFavorite userFavorite = new UserFavorite();
            userFavorite.setBizId(biz.getBizId());
            userFavorite.setBizType(biz.getBizType());
            userFavorite.setFileName(fileName + ".link");
            userFavorite.setUserFolderId(userFavoriteDTO.getUserFolderId());
            userFavorite.setMessage(userFavoriteDTO.getMessage());
            return userFavorite;
        }).collect(Collectors.toList());

        return saveBatch(userFavoriteList);
    }


    /**
     * 通过用户id和业务id删除用户已收藏的数据
     */
    @Override
    public boolean delete(Long userId, Serializable bizId) {
        if (userId == null || bizId == null || String.valueOf(bizId).trim().length() == 0) {
            log.warn("收藏数据验证失败，userId: " + userId + ", bizId: " + bizId);
            return false;
        }
        List<Long> idList = transIdToList(bizId);
        UpdateWrapper<UserFavorite> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(UserFavorite::getCreateId, userId)
                .in(UserFavorite::getBizId, idList);
        return remove(wrapper);
    }
}
